package com.mou.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mou.constant.MessageConstant;
import com.mou.dto.CartDTO;
import com.mou.entity.Cart;
import com.mou.entity.Product;
import com.mou.exception.CartErrorException;
import com.mou.mapper.CartMapper;
import com.mou.mapper.ProductMapper;
import com.mou.service.CartService;
import com.mou.vo.CartProductVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Service("cartService")
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {
    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;


    @Override
    public void add(CartDTO cartDTO) {
        Integer count =cartMapper.uniqueUserProduct(cartDTO);
        if (count>0){
            throw new CartErrorException(MessageConstant.CART_PRODUCT_EXIST);
        }else {
            Cart cart = new Cart();
            BeanUtils.copyProperties(cartDTO,cart);
            cart.setQuantity(1);
            cart.setCreateTime(LocalDate.now());
            cart.setUpdateTime(LocalDate.now());
            cartMapper.insert(cart);
        }
    }

    @Override
    public List<CartProductVO> getCartProduct(Integer id) {
        List<Cart> cartList = cartMapper.getCartById(id);
        if (!cartList.isEmpty()){
            List<CartProductVO> cartProductVOList = new ArrayList<>();
            for (Cart cart : cartList) {
                CartProductVO cartProductVO = new CartProductVO();
                Product product = productMapper.selectById(cart.getProductId());
                BeanUtils.copyProperties(cart,cartProductVO);
                cartProductVO.setProductId(product.getId());
                cartProductVO.setPrice(product.getPrice());
                cartProductVO.setProductTitle(product.getTitle());
                cartProductVO.setProductImageUrl(product.getImageUrl());
                cartProductVO.setDescription(product.getDescription());
                cartProductVOList.add(cartProductVO);
            }
           return cartProductVOList;
        }else{
            throw new CartErrorException(MessageConstant.CART_EMPTY);
        }
    }
}
